import React, { useState, useMemo, useCallback } from 'react';
import {
    Button,
    Col,
    Form,
    Input,
    Row,
    Select,
    Space,
    Spin
} from 'antd';
import {
    DownOutlined,
    UpOutlined,
    SearchOutlined,
    ReloadOutlined
} from '@ant-design/icons';
import moment from 'moment';
import { getDepartmentList, DataModel, ApiResponse } from '@/utils/api/student/student';

const { Option } = Select;

// 定义搜索参数类型
export interface SearchParams {
    name?: string;
    sex?: number;
    age?: number;
    idCard?: string;
    grade?: string;
    department?: string;
    major?: string;
    phone?: string;
}

interface SearchFormProps {
    onSearch: (params: SearchParams) => void;
    onReset: () => void;
    onDepartmentFocus?: () => void;
    onMajorFocus?: () => void;
}

// 模块级缓存和状态
let cachedDepartmentOptions: string[] = [];
let cachedAllMajorOptions: string[] = [];
let cachedDepartmentMajorMap: Map<string, string[]> = new Map();
let dataLoaded = false; // 标记数据是否已加载
let loadingPromise: Promise<boolean> | null = null; // 存储加载数据的Promise

const Search: React.FC<SearchFormProps> = ({
                                               onSearch,
                                               onReset,
                                               onDepartmentFocus,
                                               onMajorFocus,
                                           }) => {
    const [form] = Form.useForm();
    const [expand, setExpand] = useState(false);
    const [selectedDepartment, setSelectedDepartment] = useState<string>('');
    const [majorOptions, setMajorOptions] = useState<string[]>([]);
    const [departmentOptions, setDepartmentOptions] = useState<string[]>(cachedDepartmentOptions);
    const [allMajorOptions, setAllMajorOptions] = useState<string[]>(cachedAllMajorOptions);
    const [departmentMajorMap, setDepartmentMajorMap] = useState<Map<string, string[]>>(cachedDepartmentMajorMap);
    const [loading, setLoading] = useState(false);

    // 获取院系专业数据
    const fetchDepartmentData = useCallback(async () => {
        // 如果已有缓存数据，直接使用
        if (dataLoaded) {
            return true;
        }

        // 如果正在加载，返回现有的Promise
        if (loadingPromise) {
            return loadingPromise;
        }

        try {
            setLoading(true);
            // 创建并存储Promise
            loadingPromise = (async () => {
                const response = await getDepartmentList() as unknown as ApiResponse<DataModel[]>;
                if (response.code === 200) {
                    // 提取院系
                    const departments = Array.from(new Set(response.data.map((item: DataModel) => item.department)));
                    setDepartmentOptions(departments);
                    cachedDepartmentOptions = departments;

                    // 提取所有专业
                    const allMajors = Array.from(new Set(response.data.map((item: DataModel) => item.major)));
                    setAllMajorOptions(allMajors);
                    cachedAllMajorOptions = allMajors;
                    setMajorOptions(allMajors);

                    // 构建院系-专业映射
                    const map = new Map<string, string[]>();
                    response.data.forEach((item: DataModel) => {
                        if (!map.has(item.department)) map.set(item.department, []);
                        map.get(item.department)!.push(item.major);
                    });
                    setDepartmentMajorMap(map);
                    cachedDepartmentMajorMap = map;

                    dataLoaded = true;
                    return true;
                }
                return false;
            })();

            return await loadingPromise;
        } catch (error) {
            console.error('获取院系专业数据失败:', error);
            loadingPromise = null;
            return false;
        } finally {
            setLoading(false);
            loadingPromise = null;
        }
    }, []);

    // 院系选择框获取焦点时处理
    const handleDepartmentFocus = useCallback(async () => {
        if (!dataLoaded && !loadingPromise) {
            await fetchDepartmentData();
        }
        onDepartmentFocus && onDepartmentFocus();
    }, [fetchDepartmentData, onDepartmentFocus]);

    // 专业选择框获取焦点时处理
    const handleMajorFocus = useCallback(async () => {
        if (!dataLoaded && !loadingPromise) {
            await fetchDepartmentData();
        }
        onMajorFocus && onMajorFocus();
    }, [fetchDepartmentData, onMajorFocus]);

    // 院系选择变化处理
    const handleDepartmentChange = (value: string) => {
        setSelectedDepartment(value);
        form.setFieldsValue({ major: undefined });
        if (value && departmentMajorMap.has(value)) {
            setMajorOptions(departmentMajorMap.get(value) || []);
        } else {
            setMajorOptions(allMajorOptions);
        }
    };

    const handleSearch = () => {
        const values = form.getFieldsValue();

        // 类型转换与空值处理
        const params: SearchParams = {
            ...values,
            sex: values.sex !== undefined ? Number(values.sex) : undefined,
            age: values.age ? Number(values.age) : undefined
        };

        Object.keys(params).forEach(key => {
            if (params[key as keyof SearchParams] === '' || params[key as keyof SearchParams] === undefined) {
                delete params[key as keyof SearchParams];
            }
        });

        onSearch(params);
    };

    const handleReset = () => {
        form.resetFields();
        setSelectedDepartment('');
        setMajorOptions(allMajorOptions);
        onReset();
    };

    // 年级选项缓存
    const gradeOptions = useMemo(() => {
        return Array.from({ length: 11 }, (_, i) => moment().year() - 10 + i)
            .reverse()
            .map(year => (
                <Option key={year} value={String(year)}>
                    {year}级
                </Option>
            ));
    }, []);

    return (
        <Spin spinning={loading}>
            <Form
                form={form}
                name="advanced_search"
                style={{ borderRadius: '6px', marginBottom: '10px' }}
            >
                <Row gutter={24}>
                    <Col span={6}>
                        <Form.Item name="name" label="姓名">
                            <Input placeholder="请输入姓名" allowClear />
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item name="sex" label="性别">
                            <Select placeholder="请选择性别" allowClear>
                                <Option value={1}>男</Option>
                                <Option value={0}>女</Option>
                            </Select>
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item name="age" label="年龄">
                            <Input placeholder="请输入年龄" allowClear min={1} max={150} />
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item name="idCard" label="身份证号">
                            <Input placeholder="请输入身份证号" allowClear maxLength={18} />
                        </Form.Item>
                    </Col>

                    {expand && (
                        <>
                            <Col span={6}>
                                <Form.Item name="grade" label="年级">
                                    <Select placeholder="请选择年级" allowClear>
                                        {gradeOptions}
                                    </Select>
                                </Form.Item>
                            </Col>
                            <Col span={6}>
                                <Form.Item name="department" label="院系">
                                    <Select
                                        placeholder="请选择院系"
                                        allowClear
                                        onChange={handleDepartmentChange}
                                        onFocus={handleDepartmentFocus}
                                    >
                                        {departmentOptions.map(dept => (
                                            <Option key={dept} value={dept}>{dept}</Option>
                                        ))}
                                    </Select>
                                </Form.Item>
                            </Col>
                            <Col span={6}>
                                <Form.Item name="major" label="专业">
                                    <Select
                                        placeholder="请选择专业"
                                        allowClear
                                        onFocus={handleMajorFocus}
                                    >
                                        {majorOptions.map(major => (
                                            <Option key={major} value={major}>{major}</Option>
                                        ))}
                                    </Select>
                                </Form.Item>
                            </Col>
                            <Col span={6}>
                                <Form.Item name="phone" label="手机号">
                                    <Input placeholder="请输入手机号" allowClear maxLength={11} />
                                </Form.Item>
                            </Col>
                        </>
                    )}
                </Row>
                <div style={{ textAlign: 'right', marginBottom: '20px' }}>
                    <Space size="small">
                        <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>搜索</Button>
                        <Button icon={<ReloadOutlined />} onClick={handleReset}>重置</Button>
                        <a style={{ fontSize: 12 }} onClick={() => setExpand(!expand)}>
                            {expand ? <UpOutlined /> : <DownOutlined />} {expand ? '收起' : '展开'}
                        </a>
                    </Space>
                </div>
            </Form>
        </Spin>
    );
};

export default React.memo(Search);